/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[TestResourceBundle.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package api.util;

import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * java.util.ResourceBundle测试<br/>
 * 
 * 资源文件的格式: beseName_languageCode_countryCode.properties[i18n_en_US.properties]
 * <br/>
 * 要有一个默认的资源文件: baseName.properties<br/>
 * 
 * eclipse可以将properties文件中的中文自动转换为ascii编码<br/>
 * 使用jdk的命令native2ascii可以将中文转换为ascii编码<br/>
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class TestResourceBundle {

	/**
	 * 测试ResourcesBundle[locale=US]
	 */
	public static void testResourceBundle1() {
		Date today = new Date();
		String dateStr = DateFormat.getDateInstance(DateFormat.MEDIUM).format(today);

		// US
		String str = "{0} is {1} and the {2} is {3}";
		Locale locale = Locale.US;
		ResourceBundle resourceBundle = ResourceBundle.getBundle("api/util/i18n", locale);
		Enumeration<String> keys = resourceBundle.getKeys();
		while (keys.hasMoreElements()) {
			String key = keys.nextElement();
			System.out.println("key = [" + key + "] value = [" + resourceBundle.getObject(key) + "]");
		}
		String dateLabel = resourceBundle.getString("date");
		String weatherLabel = resourceBundle.getString("weather");

		String formattedMessage = MessageFormat.format(str, dateLabel, dateStr, weatherLabel, "good");
		System.out.println("After format: " + formattedMessage);
		System.out.println();
	}

	/**
	 * 测试ResourceBundle[locale=CHINA]
	 */
	public static void testResourceBundle2() {
		Date today = new Date();
		String dateStr = DateFormat.getDateInstance(DateFormat.MEDIUM).format(today);

		String str = "{0}是{1}, {2}情况是{3}";
		Locale locale = Locale.CHINA;
		ResourceBundle resourceBundle = ResourceBundle.getBundle("api/util/i18n", locale);
		Enumeration<String> keys = resourceBundle.getKeys();
		while (keys.hasMoreElements()) {
			String key = keys.nextElement();
			System.out.println("key = [" + key + "] value = [" + resourceBundle.getObject(key) + "]");
		}
		String dateLabel = resourceBundle.getString("date");
		String weatherLabel = resourceBundle.getString("weather");

		String formattedMessage = MessageFormat.format(str, dateLabel, dateStr, weatherLabel, "晴天");
		System.out.println("After format: " + formattedMessage);
		System.out.println();
	}

	public static void main(String[] args) {
		testResourceBundle1();
		testResourceBundle2();
	}
}
